"""
测试高德地图API返回的图片数据结构
"""
import os
import sys
import django

# 设置Django环境
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'travel_plan.settings')
django.setup()

from utils.amap_client import AMapClient
from django.conf import settings
import json

def test_poi_detail():
    """测试POI详情接口返回的数据结构"""
    api_key = settings.AMAP_CONFIG.get('API_KEY')
    if not api_key:
        print("错误: 未配置高德地图API Key")
        return
    
    client = AMapClient(api_key)
    
    # 先搜索POI获取实际ID
    print("=" * 60)
    print("步骤1: 搜索POI获取实际ID")
    print("=" * 60)
    
    test_keywords = ['滕王阁', '八一起义纪念馆']
    test_pois = []
    
    for keyword in test_keywords:
        print(f"\n搜索关键词: {keyword}")
        try:
            search_result = client.search_pois_by_keyword(keyword, city='南昌市', page_size=1)
            if search_result.get('status') == '1' and search_result.get('pois'):
                poi = search_result.get('pois')[0]
                poi_id = poi.get('id')
                poi_name = poi.get('name')
                print(f"  找到POI: {poi_name} (ID: {poi_id})")
                test_pois.append({'name': poi_name, 'id': poi_id})
            else:
                print(f"  未找到POI")
        except Exception as e:
            print(f"  搜索失败: {str(e)}")
    
    if not test_pois:
        print("\n错误: 未能获取到任何POI ID，无法继续测试")
        return
    
    print("=" * 60)
    print("测试高德地图API POI详情接口")
    print("=" * 60)
    
    for poi in test_pois:
        print(f"\n测试POI: {poi['name']} (ID: {poi['id']})")
        print("-" * 60)
        
        try:
            detail = client.get_poi_detail(poi['id'])
            
            if detail.get('status') == '1':
                if detail.get('pois'):
                    poi_data = detail.get('pois')[0]
                    print(f"✓ 成功获取POI详情")
                    print(f"\nPOI数据字段:")
                    print(f"  所有字段: {list(poi_data.keys())}")
                    
                    # 检查图片相关字段
                    print(f"\n图片相关字段:")
                    photo_fields = ['photos', 'photo', 'images', 'pictures', 'photos_url', 'image_url']
                    for field in photo_fields:
                        if field in poi_data:
                            value = poi_data[field]
                            print(f"  {field}: {type(value)} = {str(value)[:200]}")
                            
                            # 如果是列表，打印详细信息
                            if isinstance(value, list) and len(value) > 0:
                                print(f"    列表长度: {len(value)}")
                                print(f"    第一项: {value[0]}")
                                if isinstance(value[0], dict):
                                    print(f"    第一项字段: {list(value[0].keys())}")
                    
                    # 打印完整的poi_data（仅前1000字符）
                    print(f"\n完整POI数据预览:")
                    try:
                        poi_data_str = json.dumps(poi_data, ensure_ascii=False, indent=2)[:1000]
                        print(poi_data_str)
                    except:
                        print("无法序列化POI数据")
                else:
                    print("✗ POI数据为空")
                    print(f"响应数据: {json.dumps(detail, ensure_ascii=False, indent=2)[:500]}")
            else:
                print(f"✗ API返回错误: {detail.get('info', '未知错误')}")
        except Exception as e:
            import traceback
            print(f"✗ 异常: {str(e)}")
            print(f"错误详情:\n{traceback.format_exc()}")
    
    print("\n" + "=" * 60)
    print("测试完成")
    print("=" * 60)

if __name__ == '__main__':
    test_poi_detail()



